package io.kiki.sba.registry.common.model.appmeta;


import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Getter
public final class InterfaceMapping {

    private static final Logger LOG = LoggerFactory.getLogger(InterfaceMapping.class);

    private final long nanosVersion;
    private final Set<String> apps;

    public InterfaceMapping(long nanosVersion) {
        this.nanosVersion = nanosVersion;
        this.apps = Collections.EMPTY_SET;
    }

    public InterfaceMapping(long nanosVersion, String appName) {
        this.nanosVersion = nanosVersion;
        this.apps = Collections.singleton(appName);
    }

    public InterfaceMapping(long nanosVersion, Set<String> appNames) {
        this.nanosVersion = nanosVersion;
        this.apps = Collections.unmodifiableSet(appNames);
    }

    public InterfaceMapping addApp(long version, String app) {
        if (this.apps.contains(app) && this.nanosVersion >= version) {
            return this;
        }
        if (version <= nanosVersion) {
            LOG.error("interface app mapping stale version: {}", version);
        }
        Set<String> apps = new HashSet<>(this.apps);
        apps.add(app);
        return new InterfaceMapping(Math.max(this.nanosVersion, version), apps);
    }

    public InterfaceMapping removeApp(long version, String app) {
        if (!this.apps.contains(app) && this.nanosVersion >= version) {
            return this;
        }
        if (version <= nanosVersion) {
            LOG.error("interface app mapping stale version: {}", version);
        }
        Set<String> apps = new HashSet<>(this.apps);
        apps.remove(app);
        return new InterfaceMapping(Math.max(this.nanosVersion, version), apps);
    }


}
